package store.lunangangster.nodeflow.parser.el.operator;

import cn.hutool.core.collection.CollUtil;
import com.ql.util.express.Operator;
import store.lunangangster.nodeflow.exception.RuleSourceParseException;
import store.lunangangster.nodeflow.parser.el.OperatorHelper;
import store.lunangangster.nodeflow.rt.element.Executable;
import store.lunangangster.nodeflow.rt.element.flow.LoopFlow;
import store.lunangangster.nodeflow.util.Converter;

/**
 * 用于扩展LoopFlow的DO操作符
 *
 * @author cwk
 * @version 1.0
 */
public class DoOperator extends Operator {

  @Override
  public Object executeInner(Object[] list) throws RuleSourceParseException {
    OperatorHelper.checkArguments(list);
    if (list.length != 2) {
      throw new RuleSourceParseException("Incompatible executable for DO: should be like FOR(forNode).DO(flow)");
    }
    LoopFlow loopFlow = Converter.convert(list[0], LoopFlow.class);
    if (!CollUtil.isEmpty(loopFlow.getExecutableList())) {
      throw new RuleSourceParseException("Incompatible executable for LoopFlow: LoopFlow already has loopBody, cannot use DO() again");
    }
    Executable executable = Converter.convert(list[1], Executable.class);
    loopFlow.setExecutableList(CollUtil.toList(executable));
    return loopFlow;
  }
}
